const db = require("../config/db");

exports.getAll = async () => {
  const [rows] = await db.query("SELECT * FROM orders");
  return rows;
};

exports.add = async (order) => {
  const { customerId, merchantId, items, totalPrice, status, createdAt } =
    order;
  const [result] = await db.query(
    "INSERT INTO orders (customerId,merchantId,items,totalPrice,status,createdAt) VALUES (?,?,?,?,?,?)",
    [
      customerId,
      merchantId,
      JSON.stringify(items),
      totalPrice,
      status,
      createdAt,
    ]
  );
  return { id: result.insertId, ...order };
};

exports.update = async (id, order) => {
  const { customerId, merchantId, items, totalPrice, status, createdAt } =
    order;
  await db.query(
    "UPDATE orders SET customerId=?,merchantId=?,items=?,totalPrice=?,status=?,createdAt=? WHERE id=?",
    [
      customerId,
      merchantId,
      JSON.stringify(items),
      totalPrice,
      status,
      createdAt,
      id,
    ]
  );
  return { id, ...order };
};

exports.remove = async (id) => {
  await db.query("DELETE FROM orders WHERE id=?", [id]);
};
